package org.tonny.algorithm.leetcode;

import java.util.*;

/**
 * 53. 最大子数组和
 */
public class LeetCode53 {
    public int maxSubArray(int[] nums) {
        int max = Integer.MIN_VALUE, sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum = sum + nums[i];
            max = Math.max(max, sum);
            if (sum < 0) {//如果待加入的项小于0，则重置sum=0
                sum = 0;
            }
        }
        return max;
    }

    /**
     * 暴力解法，超时
     */
    public int maxSubArray1(int[] nums) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int res = 0;
            for (int j = i; j < nums.length; j++) {
                res = res + nums[j];
                max = Math.max(max, res);
            }
        }
        return max;
    }
}